<script setup lang="ts">
  import { ref, computed, watch, onMounted } from 'vue';
  import { DeliverySearchParam } from '@/api/inventory-management/types';
  import { deliverySearch } from '@/api/inventory-management';
  import { Notification } from '@arco-design/web-vue';
  import { useBooleanStore } from '@/store';
  import * as XLSX from 'xlsx';
  import { saveAs } from 'file-saver';
  import { byItem } from '@/api/inventory-management';

  interface TopInputType {
    modelValue: string;
    placeholder: string;
    size: 'large' | 'mini' | 'medium' | 'small';
  }

  const booleanStore = useBooleanStore();
  const emit = defineEmits(['updateArray']);
  const barcode = ref<string>('');
  const scanBarCode = computed(() => {
    if (barcode.value.includes('{')) {
      if (JSON.parse(barcode.value).CPHGZ) {
        return JSON.parse(barcode.value).CPHGZ;
      }
    }
    return barcode.value;
  });
  const itemCode = ref<string>('');
  const mProductNumber = ref<string>('');
  const qualityCode = ref<string>('');
  const wmsDeliveryPlanId = ref<string>('');
  const deliveryShop = ref<string>('');
  const aoCode = ref<string>('');
  const productCode = ref<string>('');
  const batchNo = ref<string>('');
  const startLotNo = ref<string>('');
  const endLotNo = ref<string>('');
  const requireShop = ref<string>('');
  const deliveryPlanCode = ref<string>('');
  const tableData = ref<any>();
  // 交接状态
  const deliveryStatus = ref<string>('');
  // 日期
  const deliveryDate = ref<string>('');
  // 搜索框数组
  const topInput = ref<TopInputType[]>([
    {
      modelValue: barcode.value,
      placeholder: '条码',
      size: 'large',
    },
    {
      modelValue: itemCode.value,
      placeholder: '图号',
      size: 'large',
    },
    {
      modelValue: mProductNumber.value,
      placeholder: '成品型号',
      size: 'large',
    },
    {
      modelValue: qualityCode.value,
      placeholder: '质量编号',
      size: 'large',
    },
    {
      modelValue: deliveryPlanCode.value,
      placeholder: '交接单号',
      size: 'large',
    },
    {
      modelValue: deliveryShop.value,
      placeholder: '移交单位',
      size: 'large',
    },
    {
      modelValue: requireShop.value,
      placeholder: '需求单位',
      size: 'large',
    },
    {
      modelValue: aoCode.value,
      placeholder: 'AO',
      size: 'large',
    },
    {
      modelValue: productCode.value,
      placeholder: '机型',
      size: 'large',
    },
    {
      modelValue: batchNo.value,
      placeholder: '批次',
      size: 'large',
    },
    {
      modelValue: startLotNo.value,
      placeholder: '起始架次',
      size: 'large',
    },
    {
      modelValue: endLotNo.value,
      placeholder: '截至架次',
      size: 'large',
    },
    {
      modelValue: wmsDeliveryPlanId.value,
      placeholder: '交接单ID',
      size: 'large',
    },
  ]);
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      align: 'center',
      fixed: 'left',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '交接状态',
      dataIndex: 'deliveryStatus',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '交接单类型',
      dataIndex: 'attribute5Desc',
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: 'AO',
      dataIndex: 'aoNo',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '条码',
      dataIndex: 'barcode',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '成品型号',
      dataIndex: 'mProductNumber',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      width: 130,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '交接单号',
      dataIndex: 'deliveryPlanCode',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '大件库位号',
      dataIndex: 'bulkyLocator',
      width: 130,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '标准件物料条码',
      dataIndex: 'attribute4Desc',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '移交数量',
      dataIndex: 'deliveryQty',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '接收数量',
      dataIndex: 'storageQty',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '移交人工号',
      dataIndex: 'deliveryEmpCode',
      width: 130,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '需求单位',
      dataIndex: 'requireShop',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '配送单位',
      dataIndex: 'deliveryShop',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '移交时间',
      dataIndex: 'deliveryDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '接收时间',
      dataIndex: 'receiveDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '机型',
      dataIndex: 'productCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '批次',
      dataIndex: 'batchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '起始架次',
      dataIndex: 'startLotNo',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '截至架次',
      dataIndex: 'endLotNo',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '合格证号',
      dataIndex: 'mesCheckQualitificationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '限用机型',
      dataIndex: 'xProductCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '限用批次',
      dataIndex: 'xLimitBatchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '限用架次',
      dataIndex: 'xLimitLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 120,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '交接单ID',
      dataIndex: 'wmsDeliveryPlanId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
  ];
  // 监听输入文本框的变化
  watch(
    topInput,
    (newVal) => {
      barcode.value = newVal[0].modelValue;
      itemCode.value = newVal[1].modelValue;
      mProductNumber.value = newVal[2].modelValue;
      qualityCode.value = newVal[3].modelValue;
      deliveryPlanCode.value = newVal[4].modelValue;
      deliveryShop.value = newVal[5].modelValue;
      requireShop.value = newVal[6].modelValue;
      aoCode.value = newVal[7].modelValue;
      productCode.value = newVal[8].modelValue;
      batchNo.value = newVal[9].modelValue;
      startLotNo.value = newVal[10].modelValue;
      endLotNo.value = newVal[11].modelValue;
      wmsDeliveryPlanId.value = newVal[12].modelValue;
    },
    { deep: true }
  );
  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  // 发送搜索数据
  const flowQueryData = computed<DeliverySearchParam>(() => ({
    searchParams: {
      productCode: productCode.value,
      batchNo: batchNo.value,
      startLotNo: startLotNo.value,
      endLotNo: endLotNo.value,
      wmsDeliveryPlanId: wmsDeliveryPlanId.value,
      itemCode: itemCode.value,
      qualityCode: qualityCode.value,
      barcode: scanBarCode.value,
      deliveryStatus: deliveryStatus.value,
      deliveryStatu: deliveryStatus.value === '5' ? '2' : '1',
      deliveryPlanCode: deliveryPlanCode.value,
      deliveryShop: deliveryShop.value,
      requireShop: requireShop.value,
      receiveOrgCode: '',
      mProductNumber: mProductNumber.value,
      deliveryDate: deliveryDate.value,
      aoCode: aoCode.value,
    },
    pageParameter: {
      rows: pageSize.value,
      page: pageNumber.value,
    },
  }));

  async function handleSearch() {
    const newData = await deliverySearch(flowQueryData.value);
    // console.log(newData.responseBody);
    if (newData.retCode === '200') {
      tableData.value = newData;
      emit('updateArray', newData.responseBody);
    } else {
      Notification.error({
        title: '失败',
        content: newData.message ? newData.message : '查询失败',
        closable: true,
      });
    }
  }

  function exportParam(excelData: any, excelColumns: any) {
    const emptyRows = Array(1).fill({});
    const dataWithEmptyRows = emptyRows.concat(excelData);
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(dataWithEmptyRows, {
      header: excelColumns.map((h: any) => h.dataIndex),
      skipHeader: true,
    });
    XLSX.utils.sheet_add_aoa(
      ws,
      [excelColumns.map((itemName: any) => itemName.title)],
      {
        origin: 'A1', // 表头开始的位置
      }
    );
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    saveAs(
      new Blob([wbout], { type: 'application/octet-stream' }),
      'export.xlsx'
    );
  }

  async function toExcel() {
    if (!tableData.value) {
      Notification.warning({
        title: '警告',
        content: '当前页面无需要导出数据',
        closable: true,
      });
      return;
    }
    const excelData: any = ref({
      searchParams: {
        productCode: productCode.value,
        batchNo: batchNo.value,
        startLotNo: startLotNo.value,
        endLotNo: endLotNo.value,
        wmsDeliveryPlanId: wmsDeliveryPlanId.value,
        itemCode: itemCode.value,
        qualityCode: qualityCode.value,
        barcode: scanBarCode.value,
        deliveryStatus: deliveryStatus.value,
        deliveryStatu: deliveryStatus.value === '5' ? '2' : '1',
        deliveryPlanCode: deliveryPlanCode.value,
        deliveryShop: deliveryShop.value,
        requireShop: requireShop.value,
        receiveOrgCode: '',
        mProductNumber: mProductNumber.value,
        deliveryDate: deliveryDate.value,
        aoCode: aoCode.value,
      },
      pageParameter: {
        rows: 1000000,
        page: 1,
      },
    });
    const excelDatas = await deliverySearch(excelData.value);
    // 根据列数据保留表数据，过滤多余的表格数据
    const filteredData = excelDatas.responseBody.result.map((item: any) => {
      const newItem: any = {};
      columns.forEach((column: any) => {
        if (column.dataIndex in item) {
          newItem[column.dataIndex] = item[column.dataIndex];
        }
      });
      return newItem;
    });
    exportParam(filteredData, columns);
  }

  function reset() {
    topInput.value.forEach((element) => {
      element.modelValue = '';
    });
    deliveryStatus.value = '';
    deliveryDate.value = '';
    setTimeout(() => {
      handleSearch();
    }, 150);
  }
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 30) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
  watch(
    () => booleanStore.update,
    () => {
      if (booleanStore.num6 === 14) handleSearch();
    }
  );
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col
      v-for="(input, index) in topInput"
      :key="index"
      :span="6"
      class="input-col"
    >
      <a-input
        v-model="input.modelValue"
        :placeholder="input.placeholder"
        :size="input.size"
        allow-clear
        @press-enter="handleSearch"
      ></a-input>
    </a-col>
    <a-col :span="6" class="input-col">
      <a-select
        v-model="deliveryStatus"
        default-value=""
        placeholder="交接状态"
        allow-clear
        @press-enter="handleSearch"
      >
        <a-option value="1">未确认</a-option>
        <a-option value="2">已移交</a-option>
        <a-option value="3">待入库</a-option>
        <a-option value="5">已作废</a-option>
        <a-option value="6">已入库</a-option>
        <a-option value="7">已退回</a-option>
      </a-select>
    </a-col>
    <a-col :span="6" class="input-col" @press-enter="handleSearch">
      <a-date-picker
        v-model="deliveryDate"
        placeholder="日期"
        style="width: 100%"
        allow-clear
      />
    </a-col>
  </a-row>
  <div>
    <a-button type="primary" size="large" @click="handleSearch">查询</a-button>
    <a-button class="btn-reset" size="large" @click="reset">重置</a-button>
    <a-button class="btn-reset" type="primary" size="large" @click="toExcel"
      >导出EXCEL</a-button
    >
  </div>
</template>

<style scoped>
  .input-col {
    margin-bottom: 16px;
  }
  .btn-reset {
    margin-left: 10px;
  }
</style>
